package environment.player;

import java.util.ArrayList;

import util.*;
import environment.*;

public class RolePlayer extends AbstractPlayer
{
	private int type; // 1: Defender, 2: Assistant Attacker, 3: Attacker
	
	public RolePlayer(Pitch pitch, Vector position, Team team, int type)
	{
		super(pitch, position, team);
		
		this.type = type;
	}
	
	public void update()
	{
		// assign roles
		// closest to own goal = defender
		
		type = 3; // start as an attacker
		for (Player p : pitch.getPlayers())
		{
			if (p.getTeam().equals(this.team) && p.getID() != this.ID)
			{
				double myDistance = position.euclDistance(pitch.getBall().getPosition());
				double teamMateDst = p.getPosition().euclDistance(pitch.getBall().getPosition());
				
				if (teamMateDst <= myDistance)
				{
					type--;
					if (teamMateDst == myDistance && p.getID() < this.ID) type++;
				}
			}
		}
		
		super.update();
	}
	
	public void addImmuneNetwork()
	{
		
	}
	
	public void kick(Vector impulse)
	{
		if (pitch.getBall().getVelocity().magnitude() < 0.1)
		{
			// add 20% noise to impulse
			Vector noise = new Vector(Math.random() * 2 - 1, Math.random() * 2 - 1);
			noise.normalize();
			noise.limit(impulse.magnitude() * 0.3);
			impulse.add(noise);
			
			// are we within kicking range?
			Vector distanceToBall = Vector.substract(pitch.getBall().getPosition(), position);
			if (distanceToBall.magnitude() > KICKING_RANGE)
			{
				walk(pitch.getBall().getPosition());
			}
			else
			{
				// can only shoot if ball is not moving
				if (pitch.getBall().getVelocity().magnitude() < 0.1)
				{
					long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
					
					if (timeSinceLastKick > KICK_DURATION)
					{
						pitch.getBall().kick(impulse.limit(MAX_KICK_IMPULSE));
						lastKickStartingTime = System.currentTimeMillis();
					}
				}
			}
		}
	}
	
	public void walk(Vector target)
	{
		if (pitch.getBall().getVelocity().magnitude() < 0.1)
		{
			// walks within half kickrange of target position
			
			// check if kicking movement is still in progress
			long timeSinceLastKick = System.currentTimeMillis() - lastKickStartingTime;
			if (timeSinceLastKick >= KICK_DURATION)
			{
				Vector distance = Vector.substract(target, position);
				// goal not yet reached?
				if (distance.magnitude() > KICKING_RANGE/2)
				{
					distance.limit(MAX_SPEED);
					velocity = distance;
					position.add(velocity);
				}
			}
		}
	}
}
